package utils

import (
	"crypto/md5"
	"fmt"
	"io"
	"os"
)

// MD5 获取指定字符串的md5值
func MD5(s string) string {
	_b := []byte(s)
	_sum := md5.Sum(_b)
	return fmt.Sprintf("%x", _sum)
}

// MD5Salt 获取指定字符串与salt的md5值
func MD5Salt(s, salt string) string {
	_b := []byte(s + salt)
	_sum := md5.Sum(_b)
	return fmt.Sprintf("%x", _sum)
}

// MD5RandomSalt 获取指定字符串与随机salt的md5值
func MD5RandomSalt(s string) (string, string) {
	salt := RandomStrAndNum(10)
	_b := []byte(s + salt)
	_sum := md5.Sum(_b)
	return fmt.Sprintf("%x", _sum), salt
}

// MD5File 获取指定文件的md5值
func MD5File(path string) (string, error) {
	f, err := os.Open(path)
	if err != nil {
		return "", err
	}
	defer f.Close()
	h := md5.New()
	if _, err := io.Copy(h, f); err != nil {
		return "", err
	}
	return fmt.Sprintf("%x", h.Sum(nil)), nil
}
